<?php

/**
 * Description of ContainerController
 *
 * @author Eugene I. Nezhuta
 */
class Backend_ContainerController extends RCMS_Core_BaseController {

    /**
     * Special parser that creates seo for this site.
     *
     * @var RCMS_Object_Parser_SeoParser
     */
    protected $_seoParser = null;

    public function init() {
        parent::init();
        parent::checkLogin();
        $this->_model = new Default_Model_ContainerModel();
        $this->_seoParser = new RCMS_Object_Parser_SeoParser();
        $this->view->currTheme = $this->_session->currentThemeName;
		$this->_cache->clean('all');
    }

    public function indexAction()
    {
        $this->_helper->getHelper('layout')->disableLayout();
        $this->_helper->viewRenderer->setNoRender(true);
    }

    /**
     * Add content container (AJAX called in public/js/seestem.js)
     *
     * @author Eugene I. Nezhuta
     */
    public function addcontentAction() {
		$pagesArray = $this->_model->selectPagesIdsAndNavigationName();
        $formsArray = $this->_model->selectAllForms();
        $featuredAreas = $this->getFeaturedAreasNameAsString();
        $this->_helper->getHelper('layout')->disableLayout();
        $this->view->downloadFiles = RCMS_Tools_FilesystemTools::scanDir($this->_config->website->website->path . $this->_config->website->website->downloads);
        $this->view->listFolders = RCMS_Tools_FilesystemTools::scanDir($this->_config->website->website->path . $this->_config->website->website->images);
        $this->view->fa = array_keys($this->_model->selectFeaturedAreasNames());
        $this->view->galleries = RCMS_Tools_FilesystemTools::scanDir($this->_config->website->website->path . $this->_config->website->website->galleries);
        $this->view->forms = $formsArray;
		$this->view->pages = $pagesArray;
        $this->view->variables = $this->_model->selectAllVariables();
        $widthImgs = $this->_model->selectConfigForImage();
        $this->view->widthSmallImg = $widthImgs['img_small']['value'];
        $this->view->widthMediumImg = $widthImgs['img_medium']['value'];
        $this->view->widthLargeImg = $widthImgs['img_large']['value'];
        $this->_linkListUrlForTinyMCEAction();
		$this->view->listCategories = $this->_model->selectAllCategories();
		

        $form = new RCMS_Form_TextcontainerForm();
        $form->getElement('featuredareas')->setValue($featuredAreas);
        $form->setDecorators(array(
                array('ViewScript', array('viewScript' => 'forms/addcontent.phtml'))
            ));
        $this->view->form = $form;

        $pageId = $this->getRequest()->getParam('pageId');
        if(empty ($pageId)) {
            $pageId = 0;
        } else {
            $this->view->pId = $pageId;
            $form->getElement("pageId")->setValue($pageId);
        }
        $name = $this->getRequest()->getParam('name');
        $this->view->name = $name;

			//inspired form
		$page = new RCMS_Object_Page_Page($pageId);
		$inspiredForm = new RCMS_Form_InspiredForm();
        $inspiredForm->getElement('h1')->setValue($page->getH1Tag());
        $inspiredForm->setDecorators(array(
			array('ViewScript', array('viewScript' => 'forms/inspired.phtml'))
         ));
		$this->view->currentPageId = $page->getId();
		$this->view->currentNavigationName = trim($page->getNavName());
		$this->view->inspiredForm = $inspiredForm;
		//end of inspired form
		if(!$this->getRequest()->isPost()) {
			$ctype = $this->getRequest()->getParam('type');
			$form->getElement('ctype')->setValue($ctype);
		}
        if($this->getRequest()->isPost()) {
            if($this->view->form->isValid($this->getRequest()->getParams())) {
                $user = unserialize($this->_session->currentUser);
                $containerFormData = $this->view->form->getValues();
                $container = new RCMS_Object_Container_Container();
                $container->setName($name);
				$ctype = $containerFormData['ctype'];
                $container->setType(($ctype && $ctype == RCMS_Object_Container_Container::C_TYPE_STATIC) ? RCMS_Object_Container_Container::C_TYPE_STATIC : RCMS_Object_Container_Container::C_TYPE_CONTENT);
                $container->setContent($containerFormData['admincontentarea']);
                $container->setUserId($user->getId());
                $container->setPageId($pageId);

                // $publishContent =  $this->getRequest()->getParam('publish_content');

                $container->setPublished($containerFormData['publish_content']);
                $date = "";
                if(isset($containerFormData['publish_content']) && $containerFormData['publish_content']==1)
                {
                    $date = $this->generateTodaysDate();
                }else //else 0
                {
                    if(isset($containerFormData['publish_on_date']) && $containerFormData['publish_on_date']==1){
                        if( trim($containerFormData['datepicker'])!="")
                        {
                            $date = $this->proccessPublishingDateToSql($containerFormData['datepicker']);
                        }
                    }
                }
                $container->setPublishingDate($date);
                $container->setId($container->save());
                //making seo here.
                $this->_seoParser->setContentForParsing($container->getContent());
                $this->_seoParser->updateLinkReference($container->getId());
                $this->_seoParser->replaceDeeplinksInContent();

                echo 'success';
                exit();
            }
        }
		$content = $this->_translator->processScreen($this->view->render($this->getViewScript()));
		$this->_helper->viewRenderer->setNoRender(true);
		echo $content;
    }

    /**
     * Edit text container (AJAX called in public/js/seestem.js)
     *
     * @author Eugene I. Nezhuta
     */
    public function editcontentAction() {
		$pagesArray = $this->_model->selectPagesIdsAndNavigationName();
        $formsArray = $this->_model->selectAllForms();
        $featuredAreas = $this->getFeaturedAreasNameAsString();
        $this->_helper->getHelper('layout')->disableLayout();
        $this->view->downloadFiles = RCMS_Tools_FilesystemTools::scanDir($this->_config->website->website->path . $this->_config->website->website->downloads);
        $this->view->listFolders = RCMS_Tools_FilesystemTools::scanDir($this->_config->website->website->path . $this->_config->website->website->images);
        $this->view->fa = array_keys($this->_model->selectFeaturedAreasNames());
        $this->view->forms = $formsArray;
		$this->view->pages = $pagesArray;
        $this->view->galleries = RCMS_Tools_FilesystemTools::scanDir($this->_config->website->website->path . $this->_config->website->website->galleries);
        $this->view->variables = $this->_model->selectAllVariables();
        $widthImgs = $this->_model->selectConfigForImage();
        $this->view->widthSmallImg = $widthImgs['img_small']['value'];
        $this->view->widthMediumImg = $widthImgs['img_medium']['value'];
        $this->view->widthLargeImg = $widthImgs['img_large']['value'];
        $this->_linkListUrlForTinyMCEAction();
		$this->view->listCategories = $this->_model->selectAllCategories();

        $form = new RCMS_Form_TextcontainerForm();
        $form->setDecorators(array(
                array('ViewScript', array('viewScript' => 'forms/editcontent.phtml'))
            ));
        $this->view->form = $form;
        $form->getElement('featuredareas')->setValue($featuredAreas);
        $containerId = $this->getRequest()->getParam('id');        
        $this->view->containerId = $containerId;
        $container = new RCMS_Object_Container_Container($containerId);
        $this->view->containerName = $container->getName();
        $form->getElement('admincontentarea')->setValue($container->getContent());
        $form->getElement('publish_content')->setValue($container->getPublished());
        $form->getElement("pageId")->setValue($container->getPageId());


		//inspired form
		$page = new RCMS_Object_Page_Page($container->getPageId());
		$inspiredForm = new RCMS_Form_InspiredForm();
        $inspiredForm->getElement('h1')->setValue($page->getH1Tag());
        $inspiredForm->setDecorators(array(
			array('ViewScript', array('viewScript' => 'forms/inspired.phtml'))
         ));
		$this->view->inspiredForm = $inspiredForm;
		$this->view->currentPageId = $page->getId();
		$this->view->currentNavigationName = trim($page->getNavName());
		//end of inspired form

        if($container->getPublished()!=1 && $container->getPublishingDate()!="" && $container->getPublishingDate()!="0000-00-00 00:00:00" ){
            $form->getElement('datepicker')->setValue( $this->proccessPublishingDateFromSql($container->getPublishingDate()));
            $form->getElement('publish_on_date')->setValue(0);
        }
        if($container->getPublished()==0)
        {
            $form->getElement('publish_on_date')->setValue(0);
        }
        if($container->getPublishingDate()!="" && $container->getPublishingDate()!='0000-00-00 00:00:00')
        {
            $form->getElement('publish_on_date')->setValue(1);
        }
       
       

        if($this->getRequest()->isPost()) {
            if($this->view->form->isValid($this->getRequest()->getParams())) {
                $containerFormData = $this->view->form->getValues();
                //$container->setType(RCMS_Object_Container_Container::C_TYPE_CONTENT);
                $container->setContent($containerFormData['admincontentarea']);
                $container->setPublished($containerFormData['publish_content']);
                $date = "";
                if(isset($containerFormData['publish_content']) && $containerFormData['publish_content']==1)
                {
                    $date = $this->generateTodaysDate();
                }else //else 0
                {
                    if(isset($containerFormData['publish_on_date']) && $containerFormData['publish_on_date']==1){
                        if( trim($containerFormData['datepicker'])!="")
                        {
                            $date = $this->proccessPublishingDateToSql($containerFormData['datepicker']);
                        }
                    }
                }
                $container->setPublishingDate($date);
                $result = $container->save();

                //making seo here.
                $this->_seoParser->setContentForParsing($container->getContent());
                $this->_seoParser->updateLinkReference($container->getId());
                $this->_seoParser->replaceDeeplinksInContent();

                echo 'success'; exit();
            }
        }
		$content = $this->_translator->processScreen($this->view->render($this->getViewScript()));
		$this->_helper->viewRenderer->setNoRender(true);
		echo $content;
    }

	public function addcodeAction() {
		$this->_helper->getHelper('layout')->disableLayout();
        $form = new RCMS_Form_CodeForm();
        $form->setDecorators(array(
			array('ViewScript', array('viewScript' => 'forms/addcode.phtml'))
        ));
        $this->view->form = $form;
        $pageId = $this->getRequest()->getParam('pageId');
        if(empty ($pageId)) {
            $pageId = 0;
        }
        else {
            $this->view->pId = $pageId;
        }
		$name = $this->getRequest()->getParam('name');
        $this->view->name = $name;
        if($this->getRequest()->isPost()) {
            if($this->view->form->isValid($this->getRequest()->getParams())) {
                $user = unserialize($this->_session->currentUser);
                $codeFormData = $this->view->form->getValues();
                $container = new RCMS_Object_Container_Container();
                $container->setName($name);
                $container->setType(RCMS_Object_Container_Container::C_TYPE_CODE);
                $container->setContent($this->getRequest()->getParam('inlinecode'));
                $container->setUserId($user->getId());
                $container->setPageId($pageId);
				$container->setPublishingDate(date('Y-m-d H:i:s', time()));
                $container->setId($container->save());
                echo '<script typ="text/javascript">top.location.reload();</script>';
            }
        }
		$content = $this->_translator->processScreen($this->view->render($this->getViewScript()));
		$this->_helper->viewRenderer->setNoRender(true);
		echo $content;
	}

	public function editcodeAction() {
        $this->_helper->getHelper('layout')->disableLayout();
        $form = new RCMS_Form_CodeForm();
        $form->setDecorators(array(
                array('ViewScript', array('viewScript' => 'forms/editcode.phtml'))
            ));
        $this->view->form = $form;
        $containerId = $this->getRequest()->getParam('id');
        $this->view->containerId = $containerId;
        $container = new RCMS_Object_Container_Container($containerId);
        $form->getElement('inlinecode')->setValue($container->getContent());
        if($this->getRequest()->isPost()) {
            if($this->view->form->isValid($this->getRequest()->getParams())) {
                $codeFormData = $this->view->form->getValues();
                $container->setType(RCMS_Object_Container_Container::C_TYPE_CODE);
                $container->setContent($codeFormData['inlinecode']);
                $result = $container->save();
                echo '<script typ="text/javascript">top.location.reload();</script>';
            }
        }
		$content = $this->_translator->processScreen($this->view->render($this->getViewScript()));
		$this->_helper->viewRenderer->setNoRender(true);
		echo $content;
    }

    public function addheaderAction() {
        $this->_helper->getHelper('layout')->disableLayout();
        $form = new RCMS_Form_HeaderForm();
        $form->setDecorators(array(
                array('ViewScript', array('viewScript' => 'forms/addheader.phtml'))
            ));
        $this->view->form = $form;
        $pageId = $this->getRequest()->getParam('pageId');
        if(empty ($pageId)) {
            $pageId = 0;
        }
        else {
            $this->view->pId = $pageId;
        }
        $name = $this->getRequest()->getParam('name');
        $this->view->name = $name;

		if(!$this->getRequest()->isPost()) {
			$ctype = $this->getRequest()->getParam('type');
			$form->getElement('ctype')->setValue($ctype);
		}
        if($this->getRequest()->isPost()) {
            if($this->view->form->isValid($this->getRequest()->getParams())) {
                $user = unserialize($this->_session->currentUser);
                $containerFormData = $this->view->form->getValues();
                $container = new RCMS_Object_Container_Container();
                $container->setName($name);
				$ctype = $containerFormData['ctype'];
                $container->setType(($ctype && $ctype == RCMS_Object_Container_Container::C_TYPE_STATICHEADER) ? RCMS_Object_Container_Container::C_TYPE_STATICHEADER : RCMS_Object_Container_Container::C_TYPE_HEADER);
                $container->setContent(RCMS_Tools_Tools::stripSlashesIfQuotesOn($this->getRequest()->getParam('admincontentarea')));
                $container->setUserId($user->getId());
                $container->setPageId($pageId);
				$container->setPublishingDate(date('Y-m-d H:i:s', time()));
                $container->setId($container->save());
                echo 'success'; exit();
            }
        }
		$content = $this->_translator->processScreen($this->view->render($this->getViewScript()));
		$this->_helper->viewRenderer->setNoRender(true);
		echo $content;
    }

    public function editheaderAction() {
        $this->_helper->getHelper('layout')->disableLayout();
        $form = new RCMS_Form_HeaderForm();
        $form->setDecorators(array(
                array('ViewScript', array('viewScript' => 'forms/editheader.phtml'))
            ));
        $this->view->form = $form;
        $containerId = $this->getRequest()->getParam('id');
        $this->view->containerId = $containerId;
        $container = new RCMS_Object_Container_Container($containerId);
        $form->getElement('headertext')->setValue($container->getContent());
        if($this->getRequest()->isPost()) {
            if($this->view->form->isValid($this->getRequest()->getParams())) {
                $containerFormData = $this->view->form->getValues();
                //$container->setType(RCMS_Object_Container_Container::C_TYPE_HEADER);
                $container->setContent(RCMS_Tools_Tools::stripSlashesIfQuotesOn($this->getRequest()->getParam('admincontentarea')));
                $result = $container->save();
                echo 'success'; exit();
            }
        }
		$content = $this->_translator->processScreen($this->view->render($this->getViewScript()));
		$this->_helper->viewRenderer->setNoRender(true);
		echo $content;
    }

     /**
     * This function is generate link list for TinyMCE
     *
     * @return void
     */
    private function _linkListUrlForTinyMCEAction()
    {
        $fileName = $this->_config->website->website->path . 'public/system/js/tiny_mce/link_list.js';
        try {
            if(file_exists($fileName)){
				//removing draft from pages list
				$draftCategoryId = $this->_model->selectDraftCategoryId();
                $pageListData = $this->_model->selectAllPages();
				
				if($draftCategoryId) {
					foreach($pageListData as $key => $data) {
						if($data['parentCategoryId'] == $draftCategoryId) {
							unset($pageListData[$key]);
						}
					}
				}
				sort($pageListData);
                $countPages = count($pageListData);
                $strPageList = 'var tinyMCELinkList = new Array(';
                for($i=0; $i<$countPages; $i++) {
                    $strPageList .=
					'["' . $pageListData[$i]['nav_name'] .
					'", "' . $this->getWebSiteUrl() .
					$pageListData[$i]['url'] .
					'.html~' .
					$pageListData[$i]['h1'] . '"]';
                    if($countPages != $i+1){
                        $strPageList .= ',';
                    }
                }
                $strPageList.= ');';

                if(false === file_put_contents($fileName, $strPageList)) {
                   throw new Exception("Can't save file ($fileName).");
                }
            } else {
                throw new Exception("Can't find file ($fileName) or this file doesn't exist.");
            }
        }
        catch (Exception $e) {
            echo $e->getMessage();
        }
    }
/**
 * This function generates tomorrows date
 * @return <date>
 */
    public function generateTomorrowsDate()
    {
        $date = date('m-d-Y');
        $dateArray = explode("-", $date);
        $tomorrowsDate = date("Y-m-d", mktime(0, 0, 0, $dateArray[0], ($dateArray[1])+1,$dateArray[2]));
        return $tomorrowsDate;
    }
/**
 * This function generates todays date
 * @return <date>
 */
    public function generateTodaysDate()
    {
        return date('Y-m-d');
    }
/**
 * This function generates date to sql format
 * @return <date>
 */
    public function proccessPublishingDateToSql($date)
    {
        $dateArray = explode("-", trim($date));
        $date = date("Y-m-d", mktime(0, 0, 0, $dateArray[0], $dateArray[1],$dateArray[2]));
        return $date;
    }
/**
 * This function generates date from sql format
 * @return <date>
 */
    public function proccessPublishingDateFromSql($date)
    {
        $dateArray = explode("-", trim($date));

        $timeArray = explode(" ", $dateArray[2]);

        $day = $timeArray[0];
        $date = date("m-d-Y", mktime(0, 0, 0, $dateArray[1], $day,$dateArray[0]));
        return $date;
    }

    public function getFeaturedAreasNameAsString()
    {
        $result = $this->_model->selectFeaturedAreasNames();
        $str="";
        if($result){
            foreach ($result as $key=>$value)
            {
                $str.=$key."~";
            }
        }
        return trim($str);
    }

}